package com.hyjy.music

import android.graphics.PixelFormat
import android.view.WindowManager.BadTokenException
import androidx.annotation.ColorInt
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.util.Log
import android.view.*
import android.view.View.OnTouchListener
import androidx.annotation.DrawableRes
import com.hyjy.music.databinding.LrcOnTableBinding
import com.hyjy.music.util.KEY_SWITCH_STATUS
import com.hyjy.music.util.putBoolean

/**
 * 桌面歌词辅助类
 */
object TableLrcHelper {
    private const val TAG = "TableLrcHelper"
    private val binding: LrcOnTableBinding =
        LrcOnTableBinding.inflate(LayoutInflater.from(ContextHolder.context))
    private var windowManager: WindowManager? = null
    private var layoutParams: WindowManager.LayoutParams? = null
    private var tableLrc: Pair<String?, String?>? = null
    private var title: String? = null
    private var color = 0

    /**
     * 显示桌面歌词
     */
    fun showLrcOnTable() {
        if (binding.root.windowToken != null) {
            Log.i(TAG, "isAdded, nothing to do")
        } else {
            Log.i(TAG, "showLrcOnTable,windowManager.addView()")
            windowManager =
                ContextHolder.context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            setListener()
            layoutParams = WindowManager.LayoutParams().apply {
                gravity = Gravity.CENTER
                width = WindowManager.LayoutParams.MATCH_PARENT
                height = WindowManager.LayoutParams.WRAP_CONTENT
                flags =
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                format = PixelFormat.TRANSLUCENT
                type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            }
            try {
                windowManager?.addView(binding.root, layoutParams)
            } catch (e: BadTokenException) {
                e.printStackTrace()
            }
        }
    }

    fun setTitle(title: String): TableLrcHelper {
        TableLrcHelper.title = title
        return this
    }

    fun setData(tableLrc: Pair<String?, String?>?): TableLrcHelper {
        TableLrcHelper.tableLrc = tableLrc
        return this
    }

    fun setColor(@ColorInt color: Int): TableLrcHelper {
        TableLrcHelper.color = color
        return this
    }

    fun refreshLrc() {
        Log.i(TAG, "refreshLrc")
        binding.tvTitle.text = title
        binding.tv0.setLrcContent(tableLrc?.first ?: "")
        binding.tv0.setLrcColor(color)
        binding.tv1.text = tableLrc?.second
        binding.tv1.setTextColor(Color.WHITE)
    }

    fun refreshLrcProgress(percent: Float) {
        Log.i(TAG, "refreshLrcProgress")
        binding.tv0.setLrcPercent(percent)

    }

    @SuppressLint("ClickableViewAccessibility")
    private fun setListener() {
        // 触摸桌面歌词,随手指移动
        binding.root.setOnTouchListener(object : OnTouchListener {
            var startY = 0f
            var startX = 0f
            override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
                layoutParams?.let {
                    when (motionEvent.action) {
                        MotionEvent.ACTION_DOWN -> {
                            startY = motionEvent.rawY
                            startX = motionEvent.rawX
                        }
                        MotionEvent.ACTION_MOVE -> {
                            // 竖直方向
                            val newY = motionEvent.rawY
                            val dy = newY - startY
                            it.y += dy.toInt()
                            // 水平方向
                            val newX = motionEvent.rawX
                            val dx = newX - startX
                            it.x += dx.toInt()
                            windowManager?.updateViewLayout(binding.root, layoutParams)
                            startY = newY
                            startX = newX
                        }
                        MotionEvent.ACTION_UP -> {}
                    }
                    return false
                }
                return false
            }
        })
        binding.musicControl.ivPrevious.setOnClickListener {
            onTableLrcLayoutClickListener?.onPreButtonClick()
        }
        binding.musicControl.ivPlay.setOnClickListener {
            onTableLrcLayoutClickListener?.onPlayButtonClick()
        }
        binding.musicControl.ivNext.setOnClickListener {
            onTableLrcLayoutClickListener?.onNextButtonClick()
        }
    }

    /**
     * 删除桌面歌词
     */
    fun removeLrcOnTable() {
        putBoolean(KEY_SWITCH_STATUS, false)
        if (binding.root.windowToken != null) {
            windowManager?.removeView(binding.root)
        }
    }

    /**
     * 显示播放图标
     */
    fun setImageResource(@DrawableRes res: Int) {
        binding.musicControl.ivPlay.setImageResource(res)
    }

    private var onTableLrcLayoutClickListener: OnTableLrcLayoutClickListener? = null

    fun setOnTableLrcLayoutClickListener(listener: OnTableLrcLayoutClickListener?) {
        onTableLrcLayoutClickListener = listener
    }

    interface OnTableLrcLayoutClickListener {
        fun onPlayButtonClick()
        fun onPreButtonClick()
        fun onNextButtonClick()
    }
}